package com.ly.lyyudao.service.impl;

import com.ly.lyyudao.domain.vo.AuthLoginReqVO;
import com.ly.lyyudao.domain.vo.AuthLoginRespVO;
import com.ly.lyyudao.domain.vo.ResponseResult;
import com.ly.lyyudao.security.LoginUser;
import com.ly.lyyudao.service.AuthService;
import com.ly.lyyudao.service.UsersService;
import com.ly.lyyudao.utils.JwtUtil;
import com.ly.lyyudao.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @auth wzy
 * @date 2024/5/6 17:32
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult<AuthLoginRespVO> login(AuthLoginReqVO authLoginReqVO) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(authLoginReqVO.getUsername(),authLoginReqVO.getPassword());

        Authentication authentication = authenticationManager.authenticate(authRequest);

        LoginUser loginUser = (LoginUser)authentication.getPrincipal();

        // 从数据库获取权限字符串
        List<String> perms = usersService.findPermsByUserId(loginUser.getUsers().getId());

        loginUser.setPerms(perms);

        // 登录成功后，往Redis中加入一条数据
        redisCache.setCacheObject("loginUser::"+loginUser.getUsers().getId(), loginUser,30, TimeUnit.MINUTES);

        String jwt = JwtUtil.createJWT(loginUser.getUsers().getId().toString());

        AuthLoginRespVO authLoginRespVO = new AuthLoginRespVO(loginUser.getUsers().getId(), jwt, jwt, LocalDateTime.now());

        return new ResponseResult<AuthLoginRespVO>(HttpStatus.OK.value(),"",authLoginRespVO);
    }
}
